<template>
  <el-dialog class="public-dialog" title="无法关联系统SKU" width="1100" :modelValue="modelValue" @close="handleClose" draggable align-center :close-on-click-modal="false" :append-to-body="true">
    <div>
      <div class="grid grid-cols-4">
        <!-- <VText title="平台" :value="rows.platform || ''" />
        <VText title="站点" :value="rows.site" />
        <VText title="店铺" :value="rows.shop" /> -->
        <span class="text-[14px] text-[#3A4259] leading-[20px] mr-[30px]"> <span>平台</span> {{ rows.platform || "-" }} </span>
        <span class="text-[14px] text-[#3A4259] leading-[20px] mr-[30px]"> <span>站点</span> {{ rows.site || "-" }} </span>
        <span class="text-[14px] text-[#3A4259] leading-[20px] mr-[30px]"> <span>店铺</span> {{ rows.shop || "-" }} </span>
      </div>
      <div class="grid grid-cols-4 py-[8px]">
        <!-- <VText title="系统订单号" :value="rows.order_sn" /> -->
        <!-- <VText title="平台订单号" :value="rows.platform_order_sn" /> -->
        <span class="text-[14px] text-[#3A4259] leading-[20px] mr-[30px]"> <span>系统订单号</span> {{ rows.order_sn || "-" }} </span>
        <span class="text-[14px] text-[#3A4259] leading-[20px] mr-[30px]"> <span>平台订单号：</span> {{ rows.platform_order_sn || "-" }} </span>
      </div>
      <div class="grid grid-cols-4">
        <span class="text-[14px] text-[#3A4259] leading-[20px] mb-[16px] mr-[30px]" v-for="item in amountConfig" :key="item.label">
          <span>{{ item.label }}：</span>
          <span class="font-[600]">
            {{ rows.original_order_currency }}
            {{ (item.key && rows[item.key] ? rows[item.key][item.field] : rows[item.field]) || "-" }}</span
          >
        </span>
      </div>
    </div>
    <div>商品信息</div>
    <div>
      <vxe-table ref="tableRef" :data="tableData" :round="true" maxHeight="500">
        <vxe-column field="order_item_id" title="编号" width="100"></vxe-column>
        <vxe-column title="图片" width="84">
          <template #default="{ row }">
            <el-image :src="row.main_img" width="50" height="50" style="border: 0.5px solid #f0f0f0; border-radius: 4px">
              <template #error>
                <img src="~@/assets/images/null-img.png" alt="" />
              </template>
            </el-image>
          </template>
        </vxe-column>
        <vxe-column field="origin_num" title="SKU 自定义SKU" width="170">
          <template #header>
            <div>
              <div>SKU</div>
              <div>自定义SKU</div>
            </div>
          </template>
          <template #default="{ row, rowIndex }">
            <p>{{ row.sku }}</p>
            <p>{{ row.custom_sku }}</p>
            <el-button v-if="!row.sku" type="primary" plain @click="handleAddSku(rowIndex, row)">+ 添加SKU </el-button>
          </template>
        </vxe-column>
        <vxe-column title="渠道SKU" width="140">
          <template #header>
            <div>
              <div>渠道SKU</div>
              <div>ASIN</div>
            </div>
          </template>
          <template #default="{ row }">
            <div>{{ row.platform_sku }}</div>
            <div>{{ row.asin }}</div>
            <!-- <el-select class="ml-[10px]" v-model="row.platform_sku" placeholder="请选择" allow-create filterable>
              <el-option v-for="item in skuOptions[row.sku] || []" :key="item.label" :label="item.value" :value="item.value">
              </el-option>
            </el-select> -->
          </template>
        </vxe-column>
        <vxe-column title="商品名称" field="sku_cn_title" width="120">
          <template #default="{ row }">
            <el-tooltip class="box-item" effect="dark" placement="top">
              <template #content>
                <div style="max-width: 300px">{{ row.sku_cn_title }}</div>
              </template>
              <div class="sku-title">{{ row.sku_cn_title }}</div>
            </el-tooltip>
          </template>
        </vxe-column>
        <vxe-column title="销售人员" field="sale_id" width="140">
          <template #default="{ row }">
            <select-personnel style="width: 120px" v-model:modelValue="row.sale_id" placeholder="销售人员" @change="saleChange(row)" :disabled="row.isDisabled" />
          </template>
        </vxe-column>

        <vxe-column title="物流属性" field="shipping_logistics_attr" width="88"></vxe-column>
        <vxe-column title="销售数量" field="quantity" width="88"></vxe-column>
        <vxe-column title="销售单价" field="original_price" width="88"> </vxe-column>
        <vxe-column title="销售总价" field="original_amount" width="88"> </vxe-column>
        <vxe-column title="可用库存" field="available_stock" width="88"> </vxe-column>
        <vxe-column field="opearn" title="操作" width="70" fixed="right">
          <template #default="{ row, rowIndex }">
            <el-link class="mr-2" size="small" type="primary" @click="resetProduct(rowIndex, row)" v-if="!row.isDisabled">重置 </el-link>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <template #footer>
      <div class="flex items-center justify-center py-[10px]">
        <el-button :disabled="loading" @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSave"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>
  <SelectProduct v-model:visible="visible" :multiple="false" @uploadSku="handleSku" />
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus"
import SelectProduct from "@/components/SelectProduct/index.vue"
import { getChannelSku } from "@/api/public.js"

import api from "../../api"

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  // rows: { type: Object, default: () => ({}) },
})
const rows = ref({})
const amountConfig = [
  // { label: '支付金额', field: 'pay_amount', key: 'payment' },
  // { label: '产品总价', field: 'total' },
  // { label: '运费收入', field: 'shipping_revenue' },
  // { label: '优惠金额', field: 'discount_amount' },
  { label: "支付金额", field: "original_order_amount" },
  { label: "产品总价", field: "order_amount" },
  { label: "运费收入", field: "shipping_revenue" },
  { label: "优惠金额", field: "discount_amount" },
]

const emit = defineEmits(["update:modelValue", "refresh"])

const tableRef = ref()

const tableData = ref([])
const skuOptions = ref({})
const skuLoading = ref(false)
const loading = ref(false)
const data = reactive({
  visible: false,
  rowIndex: "",
})
// const orderInfo = ref({})
const { visible, rowIndex } = toRefs(data)

const handleSave = async () => {
  try {
    loading.value = true
    const tableData = tableRef.value.getTableData().tableData

    const _emptySku = tableData.findIndex((n) => !n.sku)
    console.log(tableData)
    if (_emptySku > -1) {
      ElMessage.warning(`请补充第${_emptySku + 1}个商品sku信息!`)
      return
    }
    const _emptyPlatformSku = tableData.findIndex((n) => !n.platform_sku)
    if (_emptyPlatformSku > -1) {
      ElMessage.warning(`请补充第${_emptyPlatformSku + 1}个商品渠道sku信息!`)
      return
    }

    await api.associateSku({
      id: rows.value?.id,
      products: tableData.map((n) => ({
        platform_sku: n.platform_sku,
        sku: n.sku,
        sale_id: n.sale_id,
      })),
    })
    handleClose(1)
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

// watch(
//   () => props.rows,
//   (val) => {
//     const { items } = val
//     const total = items.reduce((pre, n) => pre + (+n.price || 0), 0)
//     orderInfo.value = {
//       ...val,
//       total,
//     }
//     items.forEach((item) => {
//       item.sale_id = item.sales_id ? item.sales_id : Number(window.userInfo?.user?.user_id)
//       item.isDisabled = !!item.sku
//     })
//     tableData.value = items
//   }
// )

const open = (val = {}) => {
  console.log(val)

  rows.value = val
  console.log(rows.value)

  const { items } = val
  // const total = items.reduce((pre, n) => pre + (+n.price || 0), 0)
  // orderInfo.value = {
  //   ...val,
  //   total,
  // }
  items.forEach((item) => {
    // item.sale_id = item.sales_id ? item.sales_id : Number(window.userInfo?.user?.user_id)
    item.sale_id = item.sku ? item.sales_id : Number(window.userInfo?.user?.user_id)

    item.isDisabled = !!item.sku
  })
  tableData.value = items
  console.log(tableData.value)
}

watch(
  () => tableData.value,
  (val) => {
    if (val && val.length > 0) {
      getSkuList(val.map((n) => n.sku))
    }
  },
  { deep: true }
)

const getSkuList = async (skuList) => {
  const { shop_id, platform } = rows.value || {}
  if (skuLoading.value) return
  try {
    skuLoading.value = true

    const { data } =
      (await getChannelSku({
        goods_sku_list: skuList,
        shop_id: shop_id,
        platform,
      })) || {}
    if (!platform) return

    const newData = data.map((n) => ({
      ...n,
      label: n.platform_sku,
      value: n.platform_sku,
    }))
    const newOptions = newData.reduce((acc, curr) => {
      let key = curr.goods_sku
      if (!acc[key]) {
        acc[key] = []
      }
      acc[key].push(curr)
      return acc
    }, {})

    skuOptions.value = newOptions
  } catch (e) {
    console.error(e)
  } finally {
    skuLoading.value = false
  }
}

const handleClose = (refresh) => {
  tableData.value = []
  // orderInfo.value = {}
  rows.value = {}
  emit("update:modelValue", false)
  if (refresh == 1) {
    emit("refresh")
  }
}

const handleAddSku = (index, row) => {
  rowIndex.value = index
  visible.value = true
  emit("addSku", index)
}

// 选择sku
const handleSku = (e) => {
  const { attr_img, sku, custom_sku, sku_cn_title, logistics_attributes_name, purchase_price } = e
  let platform_sku = tableData.value[rowIndex.value].platform_sku
  let skuData = {
    main_img: attr_img,
    sku,
    custom_sku,
    sku_cn_title,
    shipping_logistics_attr: logistics_attributes_name || "-",
    price: 0,
    available_stock: 0,
    purchase_price,
  }
  tableData.value = tableData.value.map((item) => {
    if (item.platform_sku == platform_sku) {
      item = JSON.parse(JSON.stringify({ ...item, ...skuData }))
    }
    return item
  })
  nextTick(() => {
    tableRef?.value.reloadData(tableData.value)
  })
}

const resetProduct = (index, _row) => {
  const row = {
    ..._row,
    main_img: "",
    sku: "",
    custom_sku: "",
    // platform_sku: '',
    sku_cn_title: "",
    shipping_logistics_attr: "",
    available_stock: "",
    purchase_price: "",
  }
  tableData.value[index] = Object.assign({}, row)
  nextTick(() => {
    tableRef?.value.reloadData(tableData.value)
  })
}
// 销售人员
const saleChange = (row) => {
  nextTick(() => {
    let platform_sku = row.platform_sku
    tableData.value.forEach((item) => {
      if (item.platform_sku == platform_sku) {
        item.sale_id = row.sale_id
      }
    })
  })
}

defineExpose({
  open,
})
</script>
<style lang="scss" scoped>
.sku-title {
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
}
</style>
